package com.wyf.bt

import android.app.ProgressDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.indeterminateProgressDialog
import org.jetbrains.anko.sdk25.coroutines.onItemClick
import org.jetbrains.anko.sdk25.coroutines.onQueryTextListener
import org.jetbrains.anko.sdk25.coroutines.onScrollListener
import org.jetbrains.anko.toast
import org.jetbrains.anko.uiThread
import org.jsoup.Jsoup
import java.io.IOException
import java.net.URLEncoder






class MainActivity : AppCompatActivity() {

    var page =1
    var maxPage =1
    var loadState = 0    //0 ok ;1 没有找到 ；2 加载完了
     var btList = ArrayList<Bt>()
     lateinit var adapter:IndexAdapter
    lateinit var dialog:ProgressDialog
    var kw =""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL)



        initListView()
        initSearch()

    }

    private fun initSearch() {

         index_searchView.onQueryTextListener {
             onQueryTextSubmit {
                 page =1
                 maxPage = 1
                 kw = index_searchView.query.toString()
                 loadData()
                 dialog = indeterminateProgressDialog("搜索中...","")
                 dialog.setCancelable(false)
                return@onQueryTextSubmit true
             }
         }
    }

    private fun loadData() {
        loadState = 0
        if(page>maxPage){
            toast("已经是最后一页了")
            loadState =

            return
        }

        var wrod = URLEncoder.encode(kw)

        var url = "http://www.btanv.com/search/"+wrod+"-first-asc-"+page

        doAsync {

            try {

               var  doc = Jsoup.connect(url)
                        .header("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2")
                        .get()

                var list = doc.select("div.search-item")
                if(list.size<0){
                   loadState =1
                }

                if(page==1){
                    btList.clear()
                }

                for (i in list) {

                    val title = i.select("div.item-title").first().text()
                    val url = i.select("div.item-bar > a").first().attr("href")

                   val size  = i.select("div.item-bar > span").last().child(0).text()
                    btList.add(Bt(title,url,size))

                    if(i==list[0]){
                        var le = doc.select("div.bottom-pager > a")
                        var temp = le.last().attr("href").toString()
                        temp = temp.replace("/search/"+kw+"-first-asc-","")
                        maxPage = temp.toInt()
                    }
                }

            } catch (e: IOException) {
                e.printStackTrace()
                Log.i("wyf",e.toString())
                loadState =3

            }
            uiThread {
                adapter.notifyDataSetChanged()
                dialog.hide()
                index_pb_loadmore.visibility = View.INVISIBLE
                when(loadState){
                    0 ->{

                    }
                    1->{
                        toast("没有搜索到")
                    }
                    2->{

                    }
                    3->toast("请重试")
                }
            }
        }
    }

    private fun initListView() {

        adapter = IndexAdapter(btList,this)

        index_listview.adapter = adapter
        index_listview.onItemClick { p0, p1, p2, p3 ->
            var cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            var clip = ClipData.newPlainText("bt",""+btList[p2].magnet)
            cm.primaryClip = clip
            toast("已复制到粘贴板中")

        }
        index_listview.onScrollListener {
            onScrollStateChanged { absListView, i ->

                if(i == SCROLL_STATE_IDLE){

                    if(index_pb_loadmore.visibility == View.VISIBLE){
                        return@onScrollStateChanged
                    }
                    if(index_listview.lastVisiblePosition+1 == btList.count()){
                        page++
                        index_pb_loadmore.visibility = View.VISIBLE
                        loadData()
                    }
                }

            }
        }
    }

    public override fun onResume() {
        super.onResume()
        MobclickAgent.onPageStart("SplashScreen") //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this)          //统计时长
    }

    public override fun onPause() {
        super.onPause()
        MobclickAgent.onPageEnd("SplashScreen") // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this)
    }


}
